#!/bin/sh

usage() {
 echo "Usage: $0 program ..."
 echo "or:"
 echo "Usage: $0 [OPTIONS] -- program ..."
 echo "or:"
 echo "Usage: $0 --help"
 echo
 echo "Options:"
 echo " --help               - This help"
 echo " --print-env-bash     - Print needed ENVs in bash mode"
 echo " --server SERVER      - Sets server to SERVER"
 echo " --load   MODULE      - Force loading of MODULE"
 echo " --no-load-roar       - Do not preload libroar"
 echo " --no-load-oss        - Do not preload libroaross (OSS Emulation)"
}

CMD=false

print_env=false
print_mode=none

preload_libroar='%%%PREFIX_LIB%%%/libroar.so.%%%VERSION%%% '
preload_libroaross='%%%PREFIX_LIB%%%/libroaross.so.%%%VERSION%%% '

while [ "$1" != '' ]
do
 k="$1"
 shift;

 case "$k" in
  '--')
   CMD="$1"
   shift;
   break;
  ;;
  '--server')
   export ROAR_SERVER="$1"
   shift;
  ;;
  '--load')
   LD_PRELOAD="%%%PREFIX_COMP_LIBS%%%/lib$1.so $LD_PRELOAD"
   shift;
  ;;
  '--no-load-roar')
   preload_libroar=''
  ;;
  '--no-load-oss')
   preload_libroaross=''
  ;;
  '--help'|'-h')
   usage;
   exit 0;
  ;;
  '--print-env-bash')
   print_env=true
   print_mode=bash
  ;;
  '-'*)
   echo "$0: Error: Unknown option: $k" >&2
   usage >&2;
   exit 1
  ;;
  *)
   CMD="$k"
   break;
  ;;
 esac
done

# spaces are included in $preload_*
LD_PRELOAD="$preload_libroar$preload_libroaross$LD_PRELOAD"

if [ "$LD_PRELOAD" = '' ]
then
 unset LD_PRELOAD
else
 export LD_PRELOAD
fi

if [ "$LD_LIBRARY_PATH" = '' ]
then
 export LD_LIBRARY_PATH='%%%PREFIX_COMP_LIBS%%%'
else
 export LD_LIBRARY_PATH='%%%PREFIX_COMP_LIBS%%%'":$LD_LIBRARY_PATH"
fi
export PATH='%%%PREFIX_COMP_BINS%%%'":$PATH"

if $print_env
then
 case "$print_mode" in
  'bash')
   [ "$ROAR_SERVER" != '' ] && echo "ROAR_SERVER='$ROAR_SERVER'; export ROAR_SERVER;"
   [ "$LD_PRELOAD"  != '' ] && echo "LD_PRELOAD='$LD_PRELOAD'; export LD_PRELOAD;"
   echo "LD_LIBRARY_PATH='$LD_LIBRARY_PATH'; export LD_LIBRARY_PATH;"
   echo "PATH='$PATH'; export PATH;"
  ;;
  *)
   echo "Error: unknown print env mode: $print_mode" >&2
   exit 1;
  ;;
 esac
 exit 0;
fi

exec $(exec -- echo -- 2>/dev/null) "$CMD" "$@"

#ll
